package net.maku.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import net.maku.biz.convert.BizDemocracyConvert;
import net.maku.biz.dao.BizDemocracyDao;
import net.maku.biz.entity.BizDemocracyEntity;
import net.maku.biz.query.BizDemocracyQuery;
import net.maku.biz.service.BizDemocracyService;
import net.maku.biz.vo.BizDemocracyVO;
import net.maku.framework.common.utils.PageResult;
import net.maku.framework.mybatis.service.impl.BaseServiceImpl;
import net.maku.propagate.enums.ApplyEnum;
import net.maku.system.service.SysOrgService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 民主管理
 *
 * @author 阿沐 babamu@126.com
 * @since 1.0.0 2025-03-27
 */
@Service
@AllArgsConstructor
public class BizDemocracyServiceImpl extends BaseServiceImpl<BizDemocracyDao, BizDemocracyEntity> implements BizDemocracyService {

    private final SysOrgService sysOrgService;

    @Override
    public PageResult<BizDemocracyVO> page(BizDemocracyQuery query) {
        IPage<BizDemocracyEntity> page = baseMapper.selectPage(getPage(query), getWrapper(query));
        List<BizDemocracyVO> result = BeanUtil.copyToList(page.getRecords(), BizDemocracyVO.class);
        sysOrgService.setVisible(result);
        return new PageResult<>(result, page.getTotal());
    }

    private LambdaQueryWrapper<BizDemocracyEntity> getWrapper(BizDemocracyQuery query){
        LambdaQueryWrapper<BizDemocracyEntity> wrapper = Wrappers.lambdaQuery();
        return wrapper;
    }

    @Override
    public void save(BizDemocracyVO vo) {
        BizDemocracyEntity entity = BeanUtil.copyProperties(vo, BizDemocracyEntity.class);
        baseMapper.insert(entity);
    }

    @Override
    public void update(BizDemocracyVO vo) {
        BizDemocracyEntity entity = BizDemocracyConvert.INSTANCE.convert(vo);

        updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> idList) {
        removeByIds(idList);
    }

    @Override
    public void unmount(Long id, Integer status) {
        BizDemocracyEntity entity = new BizDemocracyEntity();
        entity.setId(id);
        entity.setStatus(status);
        if (ApplyEnum.PUTAWAY.getStatus().equals(status)) {
            entity.setAuditTime(new Date());
        }
        baseMapper.updateById(entity);
    }

}